package com.dage.salesflow.service;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.util.ListUtils;
import com.dage.salesflow.constant.SysConstant;
import com.dage.salesflow.excel.model.UserExcel;
import com.dage.salesflow.kit.DbKit;
import com.dage.salesflow.kit.Ret;
import com.dage.salesflow.model.User;
import com.dage.salesflow.model.vo.QuerySql;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import io.jboot.aop.annotation.Bean;
import io.jboot.components.cache.annotation.CacheEvict;
import io.jboot.components.cache.annotation.Cacheable;
import io.jboot.db.model.Columns;

import java.util.ArrayList;
import java.util.List;

@Bean
public class UserService extends BaseService<User, UserExcel> {

	protected QuerySql listSql(User model, boolean order) {
		String select = "SELECT u.id,username,u.name,role_id,area_id,u.code,sex,weixin,phone,email,qq,id_number,status,u.remark,entry_time,r.role_name role_id_str,a.`name` area_id_str";
		String sql = "FROM t_user u\n" +
				"INNER JOIN t_role r ON u.role_id=r.id\n" +
				"INNER JOIN t_area a ON u.area_id=a.id";
		List<Object> paras = new ArrayList<>();
		if (StrKit.notBlank(model.getName())) {
			sql += " AND u.`name` like ?";
			paras.add("%" + model.getName() + "%");
		}
		if (StrKit.notBlank(model.getCode())) {
			sql += " AND u.`code` like ?";
			paras.add("%" + model.getCode() + "%");
		}
		if (StrKit.notBlank(model.getPhone())) {
			sql += " AND `phone` like ?";
			paras.add("%" + model.getPhone() + "%");
		}
		if (model.getStatus() != null) {
			sql += " AND status=?";
			paras.add(model.getStatus());
		}
		if (model.getRoleId() != null) {
			sql += " AND role_id=?";
			paras.add(model.getRoleId());
		}
		sql += dataScope(paras, "u");
		sql += " ORDER BY `create_time` DESC";
		return new QuerySql(select, sql, paras);
	}

	@Override
	public void beforeDbBatch(List<User> insertList, List<User> updateList) {
		for (User user : insertList) {
			//导入时，用户名就是姓名
			user.setUsername(user.getName());
			//导入时，默认密码000000
			user.setPassword(User.DEFAULT_PWD);
		}
	}

	@Override
	public Ret add(User model) throws Exception {
		model.setPassword(SaSecureUtil.aesEncrypt(SysConstant.PASS_WORD_KEY, model.getPassword()));
		model.setStatus(User.STATUS_NORMAL);
		return super.add(model);
	}

	public Ret login(String username, String password, boolean rememberMe) {
		User user = findByUserName(username);
		//		User user = DAO.template("user.findByUserName", username).findFirst();
		if (user != null) {
			if (SaSecureUtil.aesEncrypt(SysConstant.PASS_WORD_KEY, password).equals(user.getPassword())) {
				//				StpUtil.setLoginId(user.getId(), new SaLoginModel()
				//						.setDevice("PC")                // 此次登录的客户端设备标识, 用于[同端互斥登录]时指定此次登录的设备名称
				//						.setIsLastingCookie(rememberMe)        // 是否为持久Cookie（临时Cookie在浏览器关闭时会自动删除，持久Cookie在重新打开后依然存在）
				//						.setTimeout(SysConstant.SESSION_TIMEOUT)    // 指定此次登录token的有效期, 单位:秒 （如未指定，自动取全局配置的timeout值）
				//				);
				if (user.getStatus() == User.STATUS_LOCK) {
					return Ret.err(SysConstant.USER_LOCKED);
				}
				StpUtil.login(user.getId(), rememberMe);
				return Ret.ok();
			} else {
				return Ret.err(SysConstant.UNKNOWN_PASSWORD);
			}
		} else {
			return Ret.err(SysConstant.USER_NOT_EXIST);
		}
	}

	@Cacheable(name = SysConstant.CACHE_USER, key = "#(id)")
	public User getById(int id) {
		return findById(id);
	}

	@CacheEvict(name = SysConstant.CACHE_USER, key = "#(user.id)")
	@Override
	public boolean update(User user) {
		return super.update(user);
	}

	@CacheEvict(name = SysConstant.CACHE_USER, key = "#(user.id)")
	@Override
	public Ret edit(User user) throws Exception {
		return super.edit(user);
	}

	public User findByUserName(String userName) {
		return findFirstByColumns(Columns.create("username", userName));
	}

	/**
	 * 根据角色id查询用户数量
	 *
	 * @param roleId
	 * @return
	 */
	public long getUserNum(int roleId) {
		return Db.queryLong("SELECT COUNT(*) FROM t_user WHERE role_id=?", roleId);
	}

	/**
	 * 批量设置区域
	 */
	public Ret updateAreaByIds(int areaId, String... ids) {
		if (ids.length == 0) {
			return Ret.err("参数错误");
		}
		List<Object> paras = ListUtils.newArrayListWithExpectedSize(ids.length + 1);
		paras.add(areaId);
		StringBuilder sb = new StringBuilder("UPDATE t_user SET area_id=? WHERE id IN");
		Db.update(DbKit.buildInSqlPara(paras, sb, ids).toString(), paras.toArray());
		return Ret.ok();
	}

}
